#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2021/8/3 9:13
@File: SchedulerFlow.py
"""
import os
from time import sleep

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

from job.models import AppConfig, MenuInfo
from job.src.application.jobs import Jobs
# from upgradeTool.src.application.MainRun import ProjectFrem

from job.src.function.record_log import mylog


class SchedulerJobs():
    def __init__(self):
        self.scheduler = BlockingScheduler(timezone='Asia/Shanghai')
        self.job_list = []
        self.bscf = {"jobs": []}
        self.jobs = None
        self.pf = None
        self.__load_class()

    def __load_class(self):
        app_configs = AppConfig.objects.filter(act_type='scheduler').values("key_name", "key_value")
        shedule_class = {unit['key_name']: unit['key_value'] for unit in app_configs}
        self.addJob = shedule_class['Jobs']
        self.addPF = shedule_class['ProjectFrem']
        if self.addJob:
            self.jobs = Jobs()
        # if self.addPF:
        #     self.pf = ProjectFrem()
        # 读取app
        webPageConfig = AppConfig.objects.filter(act_type='webPage').values("key_name", "key_value")
        mylog.info(f"webPageConfig: {webPageConfig}")
        self.webPage = {}
        for unit in webPageConfig:
            if unit['key_value'] == "True":
                self.webPage[unit['key_name']] = True
            else:
                self.webPage[unit['key_name']] = unit['key_value']
        urlInfo = MenuInfo.objects.filter(title_flag=True).values('url_name', 'menu_name')
        self.webPage['urlList'] = urlInfo
        mylog.info(urlInfo)
        mylog.info(f"webPage: {self.webPage}")
        return self.webPage

    def update_bsc(self, jobconfig: list) -> dict:
        self.bscf = {"jobs": jobconfig}
        return self.bscf

    def str_to_dic(self, str_target):
        dic_res = {}
        if str_target == '':
            return dic_res
        str_list = str_target.split(',')
        for unit in str_list:
            if unit:
                key, value = unit.split(':')
                dic_res[key] = value
        return dic_res

    def add_job(self, job_id, corn, fun_name, **kwargs):
        trigger = CronTrigger(day_of_week=corn['days'], hour=corn['hour'], minute=corn['minute'])
        if fun_name == 'auto_update_script' and self.addPF:
            dic_id = {'job_id': job_id}
            kwargs.update(dic_id)
            kwargs.pop('skip_date')
            self.job_list.append(job_id)
            job = self.scheduler.add_job(self.pf.auto_update_script, trigger=trigger, coalesce=True, kwargs=kwargs,
                                   misfire_grace_time=600, id=job_id)
        elif fun_name == 'auto_update_process' and self.addPF:
            dic_id = {'job_id': job_id}
            self.job_list.append(job_id)
            job = self.scheduler.add_job(self.pf.auto_update_process, trigger=trigger, coalesce=True, kwargs=dic_id,
                                   misfire_grace_time=600, id=job_id)
        elif fun_name == 'delet_history_dirs' and self.addPF:
            self.job_list.append(job_id)
            job = self.scheduler.add_job(self.pf.delet_history_dirs, trigger=trigger, coalesce=True,
                                   misfire_grace_time=600, id=job_id)
        elif fun_name == 'query_jira_info' and self.addJob:
            self.job_list.append(job_id)
            job = self.scheduler.add_job(self.jobs.query_jira_info, trigger=trigger, coalesce=True, kwargs=kwargs,
                                   misfire_grace_time=600, id=job_id)
        elif fun_name == 'query_ts_modification' and self.addJob:
            self.job_list.append(job_id)
            job = self.scheduler.add_job(self.jobs.query_ts_modification, trigger=trigger, coalesce=True, kwargs=kwargs,
                                   misfire_grace_time=600, id=job_id)
        else:
            mylog.warn(f'{fun_name} 错误，暂无此功能！')
            job = None
        mylog.info(f'添加任务{job_id} ：{job}')
        return job

    def remove_job(self, job_id):
        if job_id in self.job_list:
            self.scheduler.remove_job(job_id)
            self.job_list.remove(job_id)
            mylog.info(f'移除任务 {job_id}')
        else:
            mylog.warn(f'不存在任务 {job_id}')

    def get_job_list(self, job_id=None):
        if job_id is not None:
            res = self.scheduler.get_job(job_id=job_id)
            res = [res]
        else:
            res = self.scheduler.get_jobs()
        mylog.info('获取的定时任务列表如下：')
        for unit in res:
            mylog.info(unit)
        return res

    def run_jobs(self):
        jobs = self.bscf['jobs']
        for job_info in jobs:
            job_id = job_info['job_id']
            flag = job_info['flag']
            if flag:
                f_name = job_info['funName']
                params = job_info.get('param', {})
                corn_time = job_info['corn_time']
                self.add_job(job_id, corn_time, f_name, **params)
            else:
                mylog.warn(f'不添加任务：{job_id}')
                # self.remove_job(job_id)
        job_list = self.get_job_list()
        return job_list

    def start_jobs(self, jobList):
        # 调度任务启动时，可以再次读取一遍参数配置，更新配置 20211119
        self.__load_class()
        # self.get_bsc()  // 从md中读取配置
        self.update_bsc(jobList)   # // 从数据库中读取配置，更新 20211119
        self.run_jobs()
        self.scheduler.start()
        sleep(0.5)
        mylog.info('-------- 启动定时任务 --------')

    def stop_jobs(self):
        self.scheduler.shutdown()
        sleep(0.5)
        mylog.info('-------- 停止定时任务 --------')